#include<iostream>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>

#define PAGE_SIZE 4096

int main(int argc,char* argv[])
{
    if(argc!=2)
    {
        std::cout<<"Usage:"<<argv[0]<<"filename"<<std::endl;
        return 1;
    }
    //1.打开目标文件mmap需要你自己先打开文件
    int fd=open(argv[1],O_RDWR|O_CREAT|O_TRUNC,0666);
    if(fd<0)
    {
        std::cout<<"Failed to open the file"<<std::endl;
        return 2;
    }
    //2.手动调整文件大小，方便合法映射
    if(ftruncate(fd,PAGE_SIZE)==-1)
    {
        std::cout<<"Failed to ftruncate"<<std::endl;
    }
    //3.文件映射
    char* shmaddr=(char*)mmap(NULL,PAGE_SIZE,PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
    if(shmaddr==MAP_FAILED)
    {
        std::cout<<"Failed to mmap"<<std::endl;
        return 3;
    }
    //4.进行文件操作
    char c='a';
    for(;c<='z';c++)
    {
        shmaddr[c-'a']=c;
        sleep(1);
    }
    //5.关闭映射
    if(munmap(shmaddr,PAGE_SIZE)==-1)
    {
        std::cout<<"Failed to munmap"<<std::endl;
        return 5;
    }
    return 0;
}